﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SRF.Common;
using SRF.UI.View; 
using SRF.Admin;
using SRF.Admin.Models;

namespace SRF.Web.Areas.Admin.Controllers
{
    [SRF.Security.Authorize]
    [SRF.Common.Logging.Log]
    public class PermissionController : Controller
    {
        static SRF.Common.Logging.ILog logger = SRF.Common.Logging.LogManager.GetLogger("PermissionController");

        PermissionService permissionService = ObjectHelper.GetObject<PermissionService>();
        DataRuleItemService dataRuleItemService = ObjectHelper.GetObject<DataRuleItemService>();

        //
        // GET: /Admin/Permission/  
        [SRF.UI.ViewTitle("功能列表")]
        public ActionResult List()
        {
            ViewBag.PermissionList = permissionService.List();

            return View();
        }

        public ActionResult ListData(string parentId)
        {
            var list = permissionService.List(parentId == "null" ? "" : parentId).Where(m => m.Type == SRF.Admin.Models.PermissionType.Module).ToList();

            return this.TreeJson(list, m => m.Id, m => m.ParentId, m => m.Name, (m, attrs) =>
            {
                attrs.Add("type", m.Type.ToString());
            });
        }

        /// <summary>
        /// 编辑功能
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        public ActionResult Edit(string id, string parentId, string parentType)
        {
            var permissionList = permissionService.List();
            ViewBag.ParentType = parentType;

            if (string.IsNullOrEmpty(id))
            {
                ViewBag.PermissionList = permissionList;
                return View();
            }
            else
            { 
                ViewBag.PermissionList = permissionList;

                var permission = permissionService.Get(id);

                return View(permission);
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(Permission permission)
        {
            var id = permissionService.Save(permission);
            if (Request.IsAjaxRequest())
            {
                return Content(id);
            }
            else
            {
                return RedirectToAction("PermissionEdit", "Admin", new { id = id });
            }
        }
        /// <summary>
        /// 查看功能
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        public ActionResult View(string id)
        {
            ViewBag.PermissionList = permissionService.List();
            if (!string.IsNullOrEmpty(id))
            {
                var permission = permissionService.Get(id);

                return View(permission);
            }
            else
                return View();
        }

        //
        // GET: /Admin/Permission/  
        [SRF.UI.ViewTitle("功能列表")]
        public ActionResult ItemList()
        {
            SRF.UI.DataSource datasource = new UI.DataSource("admin.permission.listByParentId", "admin.permission.count", m =>
            {
                m.Like("name");
                if (string.IsNullOrEmpty(Request["ParentId"]))
                {
                    m["null"] = "NULL";
                }
                else
                    m["null"] = "NOT NULL";
            });
            datasource.PerPageSize = 10;
            ViewBag.ParentId = Request["ParentId"];
            ViewBag.ParentType = Request["ParentType"];
            ViewData["name"] = Request["name"];


            return View(datasource);
        }

        public ActionResult Delete(string id)
        {
            permissionService.Delete(id);

            return Content("");
        }

        public ActionResult AuthEdit()
        {
            ViewBag.RoleList = ObjectHelper.GetObject<RoleService>().List();
            ViewBag.PermissionList = permissionService.List();
             
            return View();
        }

        public ActionResult AuthList()
        { 
            var roleList = ObjectHelper.GetObject<RoleService>().List();
            var selectList=from a in roleList
                           select new SelectListItem{
                                Text=a.Name,
                                Value=a.Id
                           };
            ViewBag.RoleSelectList = selectList;

            ViewBag.PermissionList = permissionService.List();

            var dataRuleList = ObjectHelper.GetObject<DataRuleService>().List();
            var dataRuleItemList = ObjectHelper.GetObject<DataRuleItemService>().List();
            var ruleList = (from a in dataRuleList
                            select new SRF.Web.Areas.Admin.Models.TreeNode
                            {
                                Id = a.Id,
                                Name = a.Name,
                                ParentId = ""
                            }).Union(
                           from b in dataRuleItemList
                           select new SRF.Web.Areas.Admin.Models.TreeNode
                           {
                               Id = b.Id,
                               Name = b.Name,
                               ParentId = b.DataRuleId
                           }).ToList();
            ViewBag.DataRuleList = ruleList; 

            return View();
        }

        public JsonResult GetPermissions(string roleId)
        {
            return Json(permissionService.GetActionsByRole(roleId), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetDataRuleItems(string roleId)
        { 
            return Json(dataRuleItemService.GetDataRuleItemsByRole(roleId), JsonRequestBehavior.AllowGet);
        }
          
        [HttpPost]
        public EmptyResult SaveAuth(string roleId, string[] actions, string[] dataRuleItems)
        {
            permissionService.SaveAuthorzation(roleId, actions, dataRuleItems);

            return new EmptyResult();
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            logger.Error(filterContext.RouteData.Values["action"], filterContext.Exception);

            base.OnException(filterContext);
        }
    }
}